package leetcode.L500;

public class EX59 {
    public int[][] generateMatrix(int n) {
        int[][] matrix = new int[n][n];
        int r = 1;

        int up = 0;
        int down = n-1;
        int right = n-1;
        int left = 0;

        int i = 0;
        int j = 0;
        while(true){
            for (; i < right; i++,r++) {
                matrix[j][i] = r;
            }
            up++;
            if(up>down){break;}
            for (; j < down; j++,r++) {
                matrix[j][i] = r;
            }
            right--;
            if(left>right){break;}
            for(;i>left;i--,r++){
                matrix[j][i] = r;
            }
            down--;
            if(up>down){break;}
            for(;j>up;j--,r++){
                matrix[j][i] = r;
            }
            left++;
            if(left>right){break;}
        }
        matrix[j][i] = r;
        return matrix;
    }
}
